package net.asfun.jvalog.control;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.asfun.jvalog.entity.Web;
import net.asfun.jvalog.service.SiteService;
import net.asfun.jvalog.util.RequestUtil;
import net.asfun.jvalog.util.ResponseUtil;
import net.asfun.jvalog.vo.Pager;
import net.asfun.jvalog.mvc.RequestMapping;

public class LinkController {

	
	@RequestMapping("/link")
	public String index(HttpServletRequest req, Map<String, Object> model) {
		int page = RequestUtil.getIntParam(req, "page");
		Pager pager = new Pager(page);
		model.put("links", SiteService.listAllLink(pager));
		model.put("pager", pager);
		return "links.html";
	}
	
	@RequestMapping("/link/create")
	public String create(HttpServletRequest req, Map<String, Object> model) {
		return "link.html";
	}
	
	@RequestMapping("/link/add")
	public String add(HttpServletRequest req, Map<String, Object> model) {
		String title = RequestUtil.getRequiredParam(req, "title");
		String url = RequestUtil.getRequiredParam(req, "url");
		String image = RequestUtil.getStringParam(req, "image");
		String desc = RequestUtil.getStringParam(req, "description");
		int flag = RequestUtil.getIntParam(req, "flag");
		Web web = new Web();
		web.setDescription(desc);
		web.setFlag(flag);
		web.setImage(image);
		web.setTitle(title);
		web.setUrl(url);
		SiteService.addLink(web);
		
		return ResponseUtil.feedback("link.add", req, model);
	}
	
	@RequestMapping("/link/delete")
	public String delete(HttpServletRequest req, Map<String, Object> model) {
		Long[] ids = RequestUtil.getLongParams(req, "id");
		for(int i=0; i<ids.length; i++) {
			SiteService.delete(ids[i]);
		}
		return ResponseUtil.feedback("link.delete", req, model);
	}
	
	@RequestMapping("/link/update")
	public String update(HttpServletRequest req, Map<String, Object> model) {
		Long id = RequestUtil.getLongParam(req, "id");
		String title = RequestUtil.getRequiredParam(req, "title");
		String url = RequestUtil.getRequiredParam(req, "url");
		String image = RequestUtil.getStringParam(req, "image");
		String desc = RequestUtil.getStringParam(req, "description");
		int flag = RequestUtil.getIntParam(req, "flag");
		Web web = new Web();
		web.setId(id);
		web.setDescription(desc);
		web.setFlag(flag);
		web.setImage(image);
		web.setTitle(title);
		web.setUrl(url);
		SiteService.updateLink(web);
		
		return ResponseUtil.feedback("link.update", req, model);
	}
	
	@RequestMapping("/link/edit")
	public String edit(HttpServletRequest req, Map<String, Object> model) {
		Long id = RequestUtil.getLongParam(req, "id");
		model.put("link", SiteService.getById(id));
		return "link.html";
	}
	
}
